const router = require('koa-router')()
const jwt = require("jsonwebtoken");
const { SECRET_KEY } = require("../config/index.js");
const User = require('../models/userSchema.js')
const Menu = require('../models/menuSchema.js')
const Role = require('../models/roleSchema.js')
const util = require('../utils/index.js')

router.prefix("/api/user");

// 登录
router.post("/login", async (ctx, next) => {
  const { userName, userPwd } = ctx.request.body;
  const result = await User.findOne({ userName, userPwd }, { userPwd: 0 })
  if (result) {
    // 签发 Token
    const token = jwt.sign({ data: result }, SECRET_KEY, { expiresIn: "1day" });
    result._doc.token = token
    ctx.body = util.success(result._doc, '')
  } else {
    ctx.body = util.fail('账号或密码不正确')
  }
});

// 新增
router.post('/add', async (ctx, next) => {
  let params = ctx.request.body
  const userName = params.userName
  const userEmail = params.userEmail

  try {
    // 判断用户是否存在 $or 或者
    const result1 = await User.findOne(
      { $or: [{ userName }, { userEmail }] }, '_id userName userEmail'
    )
    if (result1) {
      ctx.body = util.fail(`系统检测到有重复用户，信息如下：${result1.userName} - ${result1.userEmail}`)
      return
    }

    const result3 = await User.create(params)
    if (result3) {
      ctx.body = util.success({}, '添加用户成功')
    }
  } catch (error) {
    ctx.body = util.fail(err)
  }
})

// 编辑
router.post('/update', async (ctx, next) => {
  const { _id, ...params } = ctx.request.body
  try {
    const res = await User.findOneAndUpdate({ _id }, params)
    ctx.body = util.success({}, '更新成功')
  } catch (error) {
    ctx.body = util.fail(error)
  }
})

// 删除
router.post('/delete', async (ctx, next) => {
  // 待删除用户id数组
  const { _ids } = ctx.request.body
  try {
    const res = await User.updateMany({ _id: { $in: _ids } }, { $set: { state: 0 } })
    ctx.body = util.success({}, `共删除成功${res.modifiedCount}条`)
  } catch (error) {
    ctx.body = util.fail(error)
  }
})

// 获取所有角色列表
router.get('/allList', async (ctx) => {
  try {
    const list = await User.find({}, '_id userName userEmail')
    ctx.body = util.success(list, '')
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})

// 列表
router.get('/list', async (ctx, next) => {
  const { userName, mobile, state } = ctx.request.query
  const { page, skipIndex } = util.pager(ctx.request.query)
  let params = {}
  if (userName) params.userName = userName
  if (mobile) params.mobile = mobile
  if (state) params.state = state
  try {
    // 根据条件查询所有用户列表
    const query = User.find(params, { userPwd: 0 })
    const list = await query.skip(skipIndex).limit(page.pageSize)
    // countDocuments 统计数据
    const total = await User.countDocuments(params)
    ctx.body = util.success({
      page: {
        ...page,
        total
      },
      list
    }, '')
  } catch (error) {
    ctx.body = util.fail(error)
  }
})

// 获取用户对应的权限菜单
router.get('/permissions', async (ctx) => {
  let authorization = ctx.request.header.authorization
  let { data } = util.decoded(authorization)
  console.log('data', data);
  let menuList = await getMenuList(data.role, data.roleList)
  let actionList = await getActionList(JSON.parse(JSON.stringify(menuList)))
  ctx.body = util.success({ menuList, actionList }, '')
})

async function getMenuList(userRole, roleKeys) {
  let rootList = []
  if (userRole == 0) {
    rootList = await Menu.find({}) || []
  } else {
    // 根据用户拥有的角色，获取权限列表
    // 先查找用户对应的角色有哪些
    let roleList = await Role.find({ _id: { $in: roleKeys } })
    console.log('roleList', roleList);
    let permissionList = []
    roleList.map(role => {
      let { checkedKeys, halfCheckedKeys } = role.permissionList
      // 数组拼接
      permissionList = permissionList.concat([...checkedKeys, ...halfCheckedKeys])
    })
    // 数组去重
    permissionList = [...new Set(permissionList)]
    rootList = await Menu.find({ _id: { $in: permissionList } })
  }

  return util.getTreeMenu(rootList, null, [])
}

// 按钮权限
function getActionList(list) {
  const actionList = []
  const deep = arr => {
    while (arr.length) {
      let item = arr.pop();
      // 存储按钮权限标识
      if (item.action) {
        item.action.map(action => {
          actionList.push(action.menuCode)
        })
      }
      // 递归遍历
      if (item.children && !item.action) {
        deep(item.children);
      }
    }
  };
  deep(list)
  return actionList
}


module.exports = router
